package com.milling.web.controller.business;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.milling.business.BusinessConstants;
import com.milling.business.GlobalVariable;
import com.milling.business.domain.*;
import com.milling.business.service.*;
import com.milling.business.service.impl.WmsTaskInfoServiceImpl;
import com.milling.common.annotation.Log;
import com.milling.common.core.controller.BaseController;
import com.milling.common.core.domain.AjaxResult;
import com.milling.common.core.domain.entity.SysUser;
import com.milling.common.core.page.TableDataInfo;
import com.milling.common.core.redis.RedisCache;
import com.milling.common.enums.BusinessType;
import com.milling.common.utils.DateUtils;
import com.milling.common.utils.ExcelDrillParser;
import com.milling.common.utils.SecurityUtils;
import com.milling.common.utils.StringUtils;
import com.milling.common.utils.http.WmsApiUtils;
import com.milling.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 配针信息Controller
 *
 * @author X
 * @date 2025-03-18
 */
@RestController
@RequestMapping("/business/configinfo")
public class WmsConfigInfoController extends BaseController
{

    @Value("${wcs.tcp.macCode}")
    private String macCode;

    @Value("${storage.ip}")
    private String storageIp;

    @Value("${storage.port}")
    private int storagePort;

    @Value("${config.ip}")
    private String configIp;

    @Value("${config.port}")
    private int configPort;

    @Value("${modbus.tcp.host}")
    private String host; // 从配置文件或命令行参数中读取

    @Value("${modbus.tcp.port}")
    private int port; // 从配置文件或命令行参数中读取

    @Value("${modbus.tcp.poolSize}")
    private int poolSize; // 从配置文件或命令行参数中读取

    @Value("${modbus.tcp.slaveId}")
    private int slaveId;

//    @Autowired
//    private ModbusUtil modbusUtil;

    @Autowired
    private IWmsConfigInfoService wmsConfigInfoService;

    @Autowired
    private IWmsConfigSubService wmsConfigSubService;

    @Autowired
    private IWmsNeedleCacheService wmsNeedleCacheService;

    @Autowired
    private IWmsCellInfoService wmsCellInfoService;

    @Autowired
    private IWmsTaskInfoService wmsTaskService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IWmsErpTaskService wmsErpTaskService;

    @Autowired
    private IWmsDrillinfoStockService wmsDrillinfoStockService;

    @Autowired
    private SuspendTaskManager suspendTaskManager;

    @Autowired
    private IWmsConfigSupplyService wmsConfigSupplyService;

    @Autowired
    private IWmsConfigHoleService wmsConfigHoleService;
    @Autowired
    private WmsTaskInfoServiceImpl wmsTaskInfoServiceImpl;

//    @Autowired
//    public WebSocketServer webSocketServer;

//    @Autowired
//    private SimpMessagingTemplate messagingTemplate; // Spring提供的WebSocket消息模板
    /**
     * 查询配针信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:configinfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(WmsConfigInfo wmsConfigInfo)
    {
        startPage();

//        initSocket();

        SysUser user = SecurityUtils.getLoginUser().getUser();

        Long userId = user.getUserId();

        // 构造推送消息（包含完整任务信息）
        Map<String, Object> payload = new HashMap<>();
        payload.put("taskId", UUID.randomUUID().toString());
        payload.put("businessData", "数据变更详情");
        payload.put("type", "CONFIRMATION_ALERT");

/*
        if(1==1) {
            // 业务逻辑
            String suspendToken = suspendTaskManager.registerTask();
            throw new SuspendException("需要用户确认", suspendToken);
        }
*/

        List<WmsConfigInfo> list = wmsConfigInfoService.selectWmsConfigInfoList(wmsConfigInfo);
        return getDataTable(list);
    }

    /**
     * 导出配针信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:configinfo:export')")
    @Log(title = "配针信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmsConfigInfo wmsConfigInfo)
    {
        List<WmsConfigInfo> list = wmsConfigInfoService.selectWmsConfigInfoList(wmsConfigInfo);
        ExcelUtil<WmsConfigInfo> util = new ExcelUtil<WmsConfigInfo>(WmsConfigInfo.class);
        util.exportExcel(response, list, "配针信息数据");
    }

    /**
     * 获取配针信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:configinfo:query')")
    @GetMapping(value = "/{configId}")
    public AjaxResult getInfo(@PathVariable("configId") Long configId)
    {
        wmsDrillinfoStockService.syncStock();

        return success(wmsConfigInfoService.selectWmsConfigInfoByConfigId(configId));
    }

    /**
     * 新增配针信息
     */
    @PreAuthorize("@ss.hasPermi('business:configinfo:add')")
    @Log(title = "配针信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WmsConfigInfo wmsConfigInfo)
    {
        try {
            String fileDir = wmsConfigInfo.getFilePath().replace("profile", "czapp/uploadPath");
            logger.info("add fileDir is "+fileDir);
            List<ExcelDrillParser.Diameter> lsit = ExcelDrillParser.parseExcel(fileDir);
            for (int i = 0; i < lsit.size(); i++) {
                ExcelDrillParser.Diameter drillInfo = lsit.get(i);
                logger.info(drillInfo.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.toString());
        }

        return toAjax(wmsConfigInfoService.insertWmsConfigInfo(wmsConfigInfo));
    }

    /**
     * 修改配针信息
     */
    @PreAuthorize("@ss.hasPermi('business:configinfo:edit')")
    @Log(title = "配针信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WmsConfigInfo wmsConfigInfo)
    {
        try {
            String fileDir = wmsConfigInfo.getFilePath().replace("profile", "czapp/uploadPath");
            logger.info("edit fileDir is "+fileDir);
            List<ExcelDrillParser.Diameter> lsit = ExcelDrillParser.parseExcel(fileDir);
            for (int i = 0; i < lsit.size(); i++) {
                ExcelDrillParser.Diameter drillInfo = lsit.get(i);
                logger.info(drillInfo.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.toString());
        }
        return toAjax(wmsConfigInfoService.updateWmsConfigInfo(wmsConfigInfo));
    }

    @Log(title = "故障解除", businessType = BusinessType.OTHER)
    @PostMapping("/clearFault")
    public AjaxResult clearFault()
    {
        logger.info("开始处理 故障解除 ");

        //先执行数据回滚
        wmsConfigInfoService.rollbackData();
        //PLC地址信号处理
//        writeCoilMitsubishi(8192+4,  true);
//        try {
//            Thread.sleep(50);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        writeCoilMitsubishi(8192+4,  false);

        logger.info("处理完成 故障解除");
        return AjaxResult.success();
    }

    /**
     * 删除配针信息
     */
    @PreAuthorize("@ss.hasPermi('business:configinfo:remove')")
    @Log(title = "配针信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{configIds}")
    public AjaxResult remove(@PathVariable Long[] configIds)
    {
        return toAjax(wmsConfigInfoService.deleteWmsConfigInfoByConfigIds(configIds));
    }

    // 启动配针任务
    @Log(title = "配针信息", businessType = BusinessType.UPDATE)
    @PostMapping("/startConfiginfo")
    public AjaxResult startConfiginfo(@RequestBody WmsConfigInfo wmsConfigInfo) {
        if(wmsConfigInfo == null) {
            logger.error("配针信息为空");
            return AjaxResult.error("配针信息不能为空");
        }

        if(wmsConfigInfo.getConfigId() == null) {
            logger.error("配针ID为空");
            return AjaxResult.error("配针ID不能为空");
        }

        logger.info("开始启动配针任务，configId: {}", wmsConfigInfo.getConfigId());

        try {
/*
            @Autowired
            private ISysConfigService configService;

            String maxDrillSize = configService.selectConfigByKey("business.max_drill_size");

            if (!("true".equals(configService.selectConfigByKey("business.max_drill_size"))))
            {
                return error("当前系统没有开启注册功能！");
            }
*/

//        GlobalVariable.initConfigParam();
            wmsConfigInfoService.initConfigParam();
            logger.info("初始化配置参数完成");

            //临时注释
            wmsDrillinfoStockService.syncStock();
            logger.info("同步库存数据完成");

            //刷新缓存数据
            wmsNeedleCacheService.sysncNeedleStatus();
            logger.info("同步针盒状态完成");

            //检查状态
            logger.info("开始检查状态");

            WmsNeedleCache wmsNeedleCacheQuery = new WmsNeedleCache();
            //回流中，需回滚为有货  1空闲，2有货，3回流中，4补料中
            wmsNeedleCacheQuery.setStatus(BusinessConstants.NEEDLE_STATUS_3);
            List<WmsNeedleCache> returnList = wmsNeedleCacheService.selectWmsNeedleCacheList(wmsNeedleCacheQuery);
            if( returnList.size() > 0) {
                return AjaxResult.error("有回流任务正在执行，请执行初始化处理，配刀大托盘位置 {}", returnList.get(0).getBoxId());
            }

            //补料中，需回滚为空闲
            wmsNeedleCacheQuery.setStatus(BusinessConstants.NEEDLE_STATUS_4);
            List<WmsNeedleCache> supplyList = wmsNeedleCacheService.selectWmsNeedleCacheList(wmsNeedleCacheQuery);
            if( supplyList.size() > 0) {
                return AjaxResult.error("有补料任务正在执行，请执行初始化处理，配刀大托盘位置 {}", supplyList.get(0).getBoxId());
            }

            //补料中，需回滚为空闲
            wmsNeedleCacheQuery.setStatus(BusinessConstants.NEEDLE_STATUS_5);
            supplyList = wmsNeedleCacheService.selectWmsNeedleCacheList(wmsNeedleCacheQuery);
            if( supplyList.size() > 0) {
                return AjaxResult.error("有补料任务正在执行，请执行初始化处理，配刀大托盘位置 {}", supplyList.get(0).getBoxId());
            }

            //缓存库数据处理
            WmsCellInfo wmsCellInfoQuery = new WmsCellInfo();
            //入库中2，需处理为空闲1
            wmsCellInfoQuery.setCellStatus(BusinessConstants.CELL_STATUS_2);
            List<WmsCellInfo> inList = wmsCellInfoService.selectWmsCellInfoList(wmsCellInfoQuery);
            if (inList.size() > 0) {
                WmsCellInfo cell = inList.get(0);
                return AjaxResult.error("有入库中的任务，请执行初始化处理，缓存库位置 {"+cell.getCellId()+"} ，第 {"+cell.getsRow()+"} 行 {"+cell.getsColumn()+"} 列");
            }

            //出库中4，需处理为有货3
            wmsCellInfoQuery.setCellStatus(BusinessConstants.CELL_STATUS_4);
            List<WmsCellInfo> outList = wmsCellInfoService.selectWmsCellInfoList(wmsCellInfoQuery);
            if (outList.size() > 0) {
                WmsCellInfo cell = inList.get(0);
                return AjaxResult.error("有出库中的任务，请执行初始化处理，缓存库位置 {\"+cell.getCellId()+\"} ，第 {\"+cell.getsRow()+\"} 行 {\"+cell.getsColumn()+\"} 列\"");
            }

            //处理中 的TASK，直接删除
            WmsTaskInfo wmsTaskInfoQuery = new WmsTaskInfo();
            wmsTaskInfoQuery.setTaskStatus(BusinessConstants.TASK_STATUS_2);
            List<WmsTaskInfo> processingTasks = wmsTaskService.selectWmsTaskInfoList(wmsTaskInfoQuery);
            if (processingTasks.size() > 0) {
                return AjaxResult.error("有处理中的任务未执行完，请执行初始化清理");
            }

            //待处理 的TASK，直接删除
            wmsTaskInfoQuery.setTaskStatus(BusinessConstants.TASK_STATUS_1);
            List<WmsTaskInfo> pendingTasks = wmsTaskService.selectWmsTaskInfoList(wmsTaskInfoQuery);
            if (pendingTasks.size() > 0) {
                return AjaxResult.error("有待处理的任务没有执行完，请执行初始化清理");
            }

            //计算库存
            logger.info("开始检查库存");
            String message = checkStock(wmsConfigInfo);
            logger.info("库存检查结果: {}", message);
            if(!"ok".equals(message)){
                logger.error("库存检查失败：{}", message);
                return AjaxResult.error(message);
            }
            logger.info("库存检查通过");
            //库存充足

            WmsConfigSub wmsConfigSub = new WmsConfigSub();

            //统计配针配方
            logger.info("开始解析配针配方，configContent: {}", wmsConfigInfo.getConfigContent());
//            List<Map<String, String>> configList = genConfigMap(wmsConfigInfo.getConfigContent());
            List<Map<String, String>> configList = genConfigMap(wmsConfigInfo.getAxles().intValue(), wmsConfigInfo.getConfigContent());
            logger.info("配针配方统计完成，configList: {}", configList != null ? configList.size() : "null");

            if(configList == null || configList.isEmpty()) {
                logger.error("配针配方为空，无法启动任务");
                return AjaxResult.error("配针配方为空，无法启动任务");
            }

            for (int i = 0; i < configList.size(); i++) {
                logger.info("处理配置组 {}/{}", i+1, configList.size());
                WmsConfigSub wmsConfigSubDB = genWmsConfigSub(wmsConfigInfo, configList.get(i), i+1);
                logger.info("生成配针子项完成，configSubId: {}", wmsConfigSubDB != null ? wmsConfigSubDB.getConfigSubId() : "null");
                if(i == 0) {
                    wmsConfigSub = wmsConfigSubDB;
                }
            }
            logger.info("配针子项生成完成，最终configSubId: {}", wmsConfigSub != null ? wmsConfigSub.getConfigSubId() : "null");

            if(wmsConfigSub == null) {
                logger.error("配针子项生成失败，wmsConfigSub为null");
                return AjaxResult.error("配针子项生成失败，请检查配针配方数据");
            }

            String result = wmsConfigInfoService.startConfigTask(macCode, wmsConfigSub);
            if (StringUtils.isEmpty(result)) {
//            GlobalVariable.writeHolesFlag = false;
                redisCache.setCacheObject(GlobalVariable.WRITE_HOLES_FLAG, false);
                logger.info("配针任务启动成功");
                return AjaxResult.success("配针任务启动成功");
            } else {
                logger.error("配针任务启动失败：{}", result);
                return AjaxResult.error("配针任务启动失败：" + result);
            }

        } catch (Exception e) {
            logger.error("启动配针任务时发生异常，configId: {}", wmsConfigInfo.getConfigId(), e);
            String errorMessage = e.getMessage();
            if(errorMessage == null || errorMessage.trim().isEmpty()) {
                errorMessage = e.getClass().getSimpleName() + ": " + e.toString();
            }
            return AjaxResult.error("系统未知错误，请反馈给管理员：" + errorMessage);
        }
    }

    public Map<String, List<Integer>> convertJsonToMap(String jsonString) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(jsonString, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 工单补料任务
     * @param wmsConfigInfo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:configinfo:supply')")
    @Log(title = "配针信息", businessType = BusinessType.OTHER)
    @PostMapping("/supply")
    public AjaxResult supply(@RequestBody WmsConfigInfo wmsConfigInfo)
    {
        WmsConfigSupply wmsConfigSupplyQuery = new WmsConfigSupply();
        wmsConfigSupplyQuery.setErpTaskId(wmsConfigInfo.getErpTaskId());
        List<WmsConfigSupply> wmsConfigSupplyList = wmsConfigSupplyService.selectWmsConfigSupplyList(wmsConfigSupplyQuery);
        for (WmsConfigSupply wmsConfigSupply : wmsConfigSupplyList) {
            wmsConfigSupplyService.deleteWmsConfigSupplyById(wmsConfigSupply.getId());
        }

        wmsConfigInfoService.genConfigSupply(wmsConfigInfo);

//        wmsConfigInfoService.startConfigSupply();

        return AjaxResult.success("补料任务启动，请耐心等待处理");
    }


    private WmsConfigSub genWmsConfigSub(WmsConfigInfo wmsConfigInfo, Map<String, String> configMap, int trayId) {
        Map boxMap = analyzeConfigs(configMap);

        List boxDataList = (List<Map<Integer, String>>)boxMap.get("boxDataList"); // 存储每个盒子的数据
        Map<String, List<Integer>> fullBoxMaterialBoxNumbers = (Map<String, List<Integer>>)boxMap.get("fullBoxMaterialBoxNumbers"); // 满盒料号对应的盒子编号
        Map<String, List<Integer>> nonFullBoxMaterialBoxNumbers = (Map<String, List<Integer>>)boxMap.get("nonFullBoxMaterialBoxNumbers"); // 非满盒料号对应的盒子编号

        /*WmsConfigSub wmsConfigSubQuery = new WmsConfigSub();
        wmsConfigSubQuery.setConfigId(wmsConfigInfo.getConfigId());
        List<WmsConfigSub> wmsConfigSubList = wmsConfigSubService.selectWmsConfigSubList(wmsConfigSubQuery);
        for (int i = 0; i < wmsConfigSubList.size(); i++) {
            wmsConfigSubService.deleteWmsConfigSubByConfigSubId(wmsConfigSubList.get(i).getConfigSubId());
        }*/

        JSONArray boxDataJsonArray = (JSONArray) boxMap.get("boxDataJsonArray");
        JSONObject fullBoxJsonObject = (JSONObject) boxMap.get("fullBoxJsonObject");
        JSONObject nonFullBoxJsonObject = (JSONObject) boxMap.get("nonFullBoxJsonObject");
        WmsConfigSub wmsConfigSub = new WmsConfigSub();
        wmsConfigSub.setConfigSubContent(boxDataJsonArray.toJSONString());
        wmsConfigSub.setFullData(fullBoxJsonObject.toJSONString());
        wmsConfigSub.setMixData(nonFullBoxJsonObject.toJSONString());
//            wmsConfigSub.setTrayId(new Long(i));
        wmsConfigSub.setTrayId(new Long(trayId));
        wmsConfigSub.setConfigId(wmsConfigInfo.getConfigId());
        wmsConfigSub.setConfigSubStatus(BusinessConstants.CONFIG_STATUS_UNCONFIG);
        wmsConfigSubService.insertWmsConfigSub(wmsConfigSub);

        //更新配针状态为处理中，避免重复配针
        wmsConfigInfo.setConfigStatus(BusinessConstants.CONFIG_STATUS_PROCESSING);
        wmsConfigInfoService.updateWmsConfigInfo(wmsConfigInfo);

        //记录插针数据
        logger.info("\n解析 boxDataJsonArray：");
        List<WmsConfigHole> wmsConfigHoles = new ArrayList<>();
        for (int i = 0; i < boxDataJsonArray.size(); i++) {
            JSONObject boxData = boxDataJsonArray.getJSONObject(i);
            int boxId = boxData.getInteger("boxId");
            String boxType = boxData.getString("boxType");
            String drillInfos = boxData.getString("drillInfos");
            if (StringUtils.isNotEmpty(drillInfos)) {
                if (StringUtils.isNotEmpty(drillInfos.trim())) {
                    if (drillInfos.indexOf(",") > 0) {
                        //混料
                        String[] drillInfoArray = drillInfos.split(",");
                        for (int j = 0; j < drillInfoArray.length; j++) {
                            WmsConfigHole wmsConfigHole = new WmsConfigHole();
                            String drillinfo = drillInfoArray[j];
                            Long holeid = (i * 50) + j + 1L;
                            wmsConfigHole.setHoleId(holeid);
                            wmsConfigHole.setDrillInfo(drillinfo.trim());
                            wmsConfigHole.setConfigSubId(wmsConfigSub.getConfigSubId());
                            if(StringUtils.isNotEmpty(drillinfo.trim())) {
                                wmsConfigHole.setDrillStatus("0");
                                wmsConfigHole.setStatus("0");
                            } else {
                                wmsConfigHole.setDrillStatus("");
                                wmsConfigHole.setStatus("");
                            }
                            wmsConfigHoles.add(wmsConfigHole);
                        }
                    } else {
                        //独立料号
                        WmsConfigHole wmsConfigHole = new WmsConfigHole();
                        Long holeid = (i * 50) + 1L;
                        wmsConfigHole.setHoleId(holeid);
                        wmsConfigHole.setDrillInfo(drillInfos.trim());
                        wmsConfigHole.setConfigSubId(wmsConfigSub.getConfigSubId());
                        wmsConfigHole.setDrillStatus("0");
                        wmsConfigHole.setStatus("0");
                        wmsConfigHoles.add(wmsConfigHole);

                        for (int j = 1; j < 50; j++) {
                            wmsConfigHole = new WmsConfigHole();
                            String drillinfo = "";
                            holeid = (i * 50) + j + 1L;
                            wmsConfigHole.setHoleId(holeid);
                            wmsConfigHole.setDrillInfo(drillinfo.trim());
                            wmsConfigHole.setConfigSubId(wmsConfigSub.getConfigSubId());
                            wmsConfigHole.setDrillStatus("");
                            wmsConfigHole.setStatus("");
                            wmsConfigHoles.add(wmsConfigHole);
                        }
                    }
                }
            } else {
                //空盒
                for (int j = 0; j < 50; j++) {
                    WmsConfigHole wmsConfigHole = new WmsConfigHole();
                    String drillinfo = "";
                    Long holeid = (i * 50) + j + 1L;
                    wmsConfigHole.setHoleId(holeid);
                    wmsConfigHole.setDrillInfo(drillinfo.trim());
                    wmsConfigHole.setConfigSubId(wmsConfigSub.getConfigSubId());
                    wmsConfigHole.setDrillStatus("");
                    wmsConfigHole.setStatus("");
                    wmsConfigHoles.add(wmsConfigHole);
                }
            }
        }
        WmsConfigHole wmsConfigHoleDB = new WmsConfigHole();
        wmsConfigHoleDB.setConfigSubId(wmsConfigSub.getConfigSubId());
        List<WmsConfigHole> wmsConfigHoles1 = wmsConfigHoleService.selectWmsConfigHoleList(wmsConfigHoleDB);
        if (wmsConfigHoles1.size() > 0) {
            Long[] ids = new Long[wmsConfigHoles1.size()];
            for (int i = 0; i < wmsConfigHoles.size(); i++) {
                ids[i] = wmsConfigHoles1.get(i).getHoleId();
            }
            wmsConfigHoleService.deleteWmsConfigHoleByIds(ids);
        }

        for (int i = 0; i < wmsConfigHoles.size(); i++) {
            WmsConfigHole wmsConfigHole = wmsConfigHoles.get(i);
            wmsConfigHoleService.insertWmsConfigHole(wmsConfigHole);
        }

        return wmsConfigSub;
    }

    private String checkStock(WmsConfigInfo wmsConfigInfo) {
        logger.info("开始检查库存，configId: {}, erpTaskId: {}", wmsConfigInfo.getConfigId(), wmsConfigInfo.getErpTaskId());

        try {
            if(wmsErpTaskService == null) {
                logger.error("wmsErpTaskService为null");
                return "系统服务未初始化";
            }

            WmsErpTask wmsErpTask = wmsErpTaskService.selectWmsErpTaskById(wmsConfigInfo.getErpTaskId());
            if(wmsErpTask == null) {
                logger.error("ERP任务不存在，erpTaskId: {}", wmsConfigInfo.getErpTaskId());
                return "ERP任务不存在";
            }

            if(wmsErpTask.getConfigData() == null || wmsErpTask.getConfigData().trim().isEmpty()) {
                logger.error("ERP任务配置数据为空，erpTaskId: {}", wmsConfigInfo.getErpTaskId());
                return "ERP任务配置数据为空";
            }

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = null;
            try {
                jsonNode = objectMapper.readTree(wmsErpTask.getConfigData());
            } catch (JsonProcessingException e) {
                logger.error("JSON解析失败，erpTaskId: {}", wmsConfigInfo.getErpTaskId(), e);
                return "配置数据格式错误";
            }

            JsonNode drillArray = jsonNode.get("drillArray");
            if(drillArray == null) {
                logger.error("钻针数组不存在，erpTaskId: {}", wmsConfigInfo.getErpTaskId());
                return "钻针配置数据缺失";
            }

//        JsonNode drillArray = JSONArray.parse(wmsErpTask.getConfigData()).get("drillArray");
//                JSONObject.parse(wmsErpTask.getConfigData()).get("drillArray");
            List<String> lines = new ArrayList<>();
            // 收集主刀盒中的刀具
            for (JsonNode tool : drillArray) {
                if(tool != null && tool.get("drillInfo") != null) {
                    lines.add(tool.get("drillInfo").asText());
                }
            }

//        List<String> lines = new ArrayList<>();
            Map<String, Integer> allmap = new HashMap<>();
            Map<String, Integer> fullmap = new HashMap<>();
            int blockSize = 50; // 每块的大小
            String message = "ok";

            // 检查lines是否为空
            if(lines.isEmpty()) {
                logger.warn("钻针数据为空");
                return "钻针数据为空，无法进行库存检查";
            }

            // 遍历数组，每50个元素为一个块
            for (int i = 0; i < lines.size(); i += blockSize) {
                int end = Math.min(i + blockSize, lines.size());
                String currentDrillinfo = lines.get(i);

                // 检查currentDrillinfo是否为null或空
                if(currentDrillinfo == null || currentDrillinfo.trim().isEmpty()) {
                    logger.warn("发现空的钻针信息，位置: {}", i);
                    continue; // 跳过空的钻针信息
                }

                // 检查当前块的所有元素是否相同
                boolean allSame = true;
                for (int j = i; j < end; j++) {
                    String drillinfo = lines.get(j);
                    if(drillinfo == null || !drillinfo.equals(currentDrillinfo)) {
                        allSame = false;
                        break;
                    }
                }

                if (allSame) {
                    if (fullmap.containsKey(currentDrillinfo)) {
                        fullmap.put(currentDrillinfo, (Integer) fullmap.get(currentDrillinfo) + blockSize);
                    } else {
                        fullmap.put(currentDrillinfo, blockSize);
                    }
                }

                // 更新 map 的统计信息
                for (int j = i; j < end; j++) {
                    String drillinfo = lines.get(j);
                    // 跳过null或空的钻针信息
                    if(drillinfo == null || drillinfo.trim().isEmpty()) {
                        continue;
                    }
                    if (!allmap.containsKey(drillinfo)) {
                        allmap.put(drillinfo, 1);
                    } else {
                        allmap.put(drillinfo, allmap.get(drillinfo) + 1);
                    }
                }
            }

            // 输出结果
            //需要补针的数据为 总量 - 整盒数量
            logger.info("统计每种钻针所需的总量: " + allmap);
            logger.info("统计整盒的钻针数量: " + fullmap);

            if(allmap.isEmpty()) {
                logger.warn("allmap为空，没有统计到钻针数据");
                return "没有统计到钻针数据";
            }

            //满盒补料
            WmsCellInfo wmsCellInfoQuery = new WmsCellInfo();
//        wmsCellInfoQuery.setDrillCount(new Long(50));
            if(BusinessConstants.CELL_STATUS_3 == null) {
                logger.error("BusinessConstants.CELL_STATUS_3为null");
                return "系统常量未初始化";
            }
            wmsCellInfoQuery.setCellStatus(BusinessConstants.CELL_STATUS_3);

            if(wmsCellInfoService == null) {
                logger.error("wmsCellInfoService为null");
                return "系统服务未初始化";
            }

            List<Map> cellList = wmsCellInfoService.selectCellStock(wmsCellInfoQuery);
            Map<String, Long> cellMap = new HashMap<>();
            if(cellList != null) {
                for (Map tmpmap : cellList) {
                    if(tmpmap != null) {
                        Object countObj = tmpmap.get("drill_cell_count");
                        Object drillInfoObj = tmpmap.get("drill_info");
                        if(countObj != null && drillInfoObj != null) {
                            BigDecimal count = (BigDecimal) countObj;
                            String drillInfo = (String) drillInfoObj;
                            cellMap.put(drillInfo, count.longValue());
                            logger.info("cellMap drillinfo " + drillInfo + " count " + count.longValue());
                        }
                    }
                }
            }

            //配针托盘补料
            if(wmsNeedleCacheService == null) {
                logger.error("wmsNeedleCacheService为null");
                return "系统服务未初始化";
            }

            List<Map> needleList = wmsNeedleCacheService.selectNeedleStock(new WmsNeedleCache());
            Map<String, Long> needleMap = new HashMap<>();
            if(needleList != null) {
                for (Map tmpmap : needleList) {
                    if(tmpmap != null) {
                        Object countObj = tmpmap.get("drill_needle_count");
                        Object drillInfoObj = tmpmap.get("drill_info");
                        if(countObj != null && drillInfoObj != null) {
                            BigDecimal count = (BigDecimal) countObj;
                            String drillInfo = (String) drillInfoObj;
                            needleMap.put(drillInfo, count.longValue());
                            logger.info("needleMap drillinfo " + drillInfo + " count " + count.longValue());
                        }
                    }
                }
            }

            logger.info("开始检查库存充足性，总共有{}种钻针需要检查", allmap.size());
            //这里检查库存时，需要算上轴数 allmap 里的tempcount * 轴数
            Iterator<Map.Entry<String, Integer>> iteratorAll = allmap.entrySet().iterator();
            while (iteratorAll.hasNext()) {
                Map.Entry<String, Integer> entry = iteratorAll.next();
                String tempdrillinfo = entry.getKey();
                Integer tempcount = entry.getValue();

                logger.info("检查钻针: {}, 需要数量: {}", tempdrillinfo, tempcount);
                int needleCount = 0;
                if(null != needleMap.get(tempdrillinfo) && needleMap.get(tempdrillinfo) > 0) {
                    needleCount = needleMap.get(tempdrillinfo).intValue();
                }
                int cellCount = 0;
                if(null != cellMap.get(tempdrillinfo) && cellMap.get(tempdrillinfo) > 0) {
                    cellCount = cellMap.get(tempdrillinfo).intValue();
                }
                int stockCount = 0;
                try {
                    WmsApiUtils wmsApiUtils = new WmsApiUtils();
                    Map<String, Integer> stockMap = wmsApiUtils.queryInventoryV1();
                    if (stockMap != null && stockMap.get(tempdrillinfo) != null && stockMap.get(tempdrillinfo) > 0) {
                        stockCount = stockMap.get(tempdrillinfo).intValue();
                    }
                } catch (Exception e) {
                    logger.error("查询库存API失败，钻针: {}", tempdrillinfo, e);
                    // 库存查询失败时，stockCount保持为0，继续处理
                }

            /*if(needleCount < tempcount) {
                logger.info("针号：" + tempdrillinfo + " 配针盘 + 缓存库库存不足，请缓存及时补料！");//继续询问缓存库是否充足
                redisCache.setCacheObject("CONFIG_STOCK-" + tempdrillinfo, "NEEDLE_FAIL");
                if(cellCount + needleCount < tempcount) {
                    logger.info("针号：" + tempdrillinfo + " 配针盘 + 缓存库库存不足，请后库及时补料！");//继续询问后库是否充足
                    redisCache.setCacheObject("CONFIG_STOCK-" + tempdrillinfo, "CACHE_FAIL");
                    if (stockCount + cellCount + needleCount < tempcount) {
                        message = "针号：" + tempdrillinfo + " 配针盘 + 缓存库 + 后库 总库存不足，不能配针！";
                        logger.info(message);
                        return message;
                    } else {
                        //后库库存充足
                        redisCache.setCacheObject("CONFIG_STOCK-" + tempdrillinfo, "STOCK_OK");
                    }
                } else {
                    //缓存库库存充足
                    redisCache.setCacheObject("CONFIG_STOCK-" + tempdrillinfo, "CACHE_OK");
                }
            } else {
                //配针盘库存充足
                redisCache.setCacheObject("CONFIG_STOCK-" + tempdrillinfo, "NEEDLE_OK");
            }*/

                if(needleCount >= tempcount) {
//                logger.info("针号：" + tempdrillinfo + " 配针盘大托盘库存足够配针！");//继续询问缓存库是否充足
                } else if(cellCount + needleCount >= tempcount) {
//                logger.info("针号：" + tempdrillinfo + " 配针盘 + 缓存库库存足够配针！");//继续询问后库是否充足
                } else if (stockCount + cellCount + needleCount >= tempcount) {
//                logger.info("针号：" + tempdrillinfo + " 配针盘 + 缓存库 + 后库库存足够配针！");//继续询问后库是否充足
                } else {
                    message = "针号：" + tempdrillinfo + " 库存不足，不能配针！";
                    logger.info(message);
                    return message;
                }
            }
            return message;

        } catch (Exception e) {
            logger.error("检查库存时发生异常", e);
            String errorMessage = e.getMessage();
            if (errorMessage == null || errorMessage.trim().isEmpty()) {
                errorMessage = e.getClass().getSimpleName() + ": " + e.toString();
            }
            return "库存检查异常: " + errorMessage;
        }
    }

    //    public List<Map<Integer, String>> analyzeConfigs(Map<String, String> configMap) {
    //    public Map analyzeConfigs(Map<String, String> configMap) {
    //public Map analyzeConfigs(Map<String, String> configMap) {
    public Map  analyzeConfigs(Map<String, String> configMap) {
        int totalBoxes = 16; // 总共有16个针盒
        int holesPerBox = 50; // 每个针盒有50个孔
        int totalHoles = totalBoxes * holesPerBox; // 总共800个孔

        // 创建一个列表来存储所有孔位的数据，按顺序填充
        List<String> configList = new ArrayList<>();
        for (int i = 1; i <= totalHoles; i++) {
            String key = "Config" + i;
            String value = configMap.getOrDefault(key, ""); // 如果不存在，默认为空
            // 将空格也视为没有料号
            if (value.trim().isEmpty()) {
                configList.add("");
            } else {
                configList.add(value);
            }
        }

        List<Map<Integer, String>> boxDataList = new ArrayList<>(); // 存储每个盒子的数据
        Map<String, List<Integer>> fullBoxMaterialBoxNumbers = new HashMap<>(); // 满盒料号对应的盒子编号
        Map<String, List<Integer>> nonFullBoxMaterialPositions = new HashMap<>(); // 非满盒料号位置

        for (int boxIndex = 0; boxIndex < totalBoxes; boxIndex++) {
            int startIndex = boxIndex * holesPerBox;
            int endIndex = startIndex + holesPerBox;
            List<String> currentBox = configList.subList(startIndex, endIndex);

            // 记录当前盒子的全局孔位起始位置（1-based）
            int globalStartIndex = boxIndex * holesPerBox + 1;
            int globalEndIndex = globalStartIndex + holesPerBox - 1;

            // 检查是否为空盒
            boolean isEmptyBox = true;
            for (String hole : currentBox) {
                if (!hole.isEmpty()) {
                    isEmptyBox = false;
                    break;
                }
            }

            Map<Integer, String> boxData = new HashMap<>();
            boxData.put(boxIndex + 1, ""); // 初始化盒子号，值为空

            if (isEmptyBox) {
                // 空盒
                boxData.put(boxIndex + 1, "");
            } else {
                // 检查是否为满盒
                String firstMaterial = currentBox.get(0);
                boolean isFullBox = true;
                boolean hasEmptyHole = false;
                boolean isMixedBox = false;

                for (String hole : currentBox) {
                    if (hole.isEmpty()) {
                        hasEmptyHole = true;
                        break;
                    }
                    if (!hole.equals(firstMaterial)) {
                        isFullBox = false;
                        isMixedBox = true;
                    }
                }

                if (isFullBox && !hasEmptyHole) {
                    // 满盒
                    boxData.put(boxIndex + 1, firstMaterial);
                    // 记录满盒料号对应的盒子编号
                    fullBoxMaterialBoxNumbers.computeIfAbsent(firstMaterial, k -> new ArrayList<>())
                            .add(boxIndex + 1);
                } else {
                    // 构建非满盒的输出字符串
                    if (isMixedBox && !hasEmptyHole) {
                        // 混针盒
                        StringBuilder sb = new StringBuilder();
//                        sb.append("混针盒: ");
                        for (int i = 0; i < currentBox.size(); i++) {
                            if (i > 0) {
                                sb.append(", ");
                            }
                            sb.append(currentBox.get(i));
                        }
                        boxData.put(boxIndex + 1, sb.toString());
                    } else {
                        // 非满盒
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < currentBox.size(); i++) {
                            if (i > 0) {
                                sb.append(", ");
                            }
                            sb.append(currentBox.get(i).isEmpty() ? "" : currentBox.get(i));
                        }
                        boxData.put(boxIndex + 1, sb.toString());
                    }

                    // 记录非满盒中每个料号的孔位位置
                    for (int i = 0; i < currentBox.size(); i++) {
                        String material = currentBox.get(i);
                        if (!material.isEmpty()) {
                            // 计算全局孔位位置
                            int globalHoleIndex = globalStartIndex + i;
                            // 记录料号位置
                            nonFullBoxMaterialPositions.computeIfAbsent(material, k -> new ArrayList<>())
                                    .add(globalHoleIndex);
                        }
                    }
                }
            }

            boxDataList.add(boxData);
        }

        // 构建 boxDataList 的 JSON 对象
        JSONArray boxDataJsonArray = new JSONArray();
        for (Map<Integer, String> boxData : boxDataList) {
            for (Map.Entry<Integer, String> entry : boxData.entrySet()) {
                int boxId = entry.getKey();
                String boxContent = entry.getValue();

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("boxId", boxId);

                if ("".equals(boxContent)) {
                    jsonObject.put("boxType", "EMPTY");
                    jsonObject.put("drillInfos", "");
                } else if (boxContent.contains(",")) {
                    jsonObject.put("boxType", "MIX");
                    jsonObject.put("drillInfos", boxContent);
                } else {
                    jsonObject.put("boxType", "FULL");
                    jsonObject.put("drillInfos", boxContent);
                }

                boxDataJsonArray.add(jsonObject);
            }
        }

        // 构建 fullBoxMaterialBoxNumbers 的 JSON 对象
        JSONObject fullBoxJsonObject = new JSONObject();
        for (Map.Entry<String, List<Integer>> entry : fullBoxMaterialBoxNumbers.entrySet()) {
            JSONArray boxNumbers = new JSONArray();
            for (Integer boxNumber : entry.getValue()) {
                boxNumbers.add(boxNumber);
            }
            fullBoxJsonObject.put(entry.getKey(), boxNumbers);
        }

        // 构建 nonFullBoxMaterialPositions 的 JSON 对象
        JSONObject nonFullBoxJsonObject = new JSONObject();
        for (Map.Entry<String, List<Integer>> entry : nonFullBoxMaterialPositions.entrySet()) {
            JSONArray positions = new JSONArray();
            for (Integer position : entry.getValue()) {
                positions.add(position);
            }
            nonFullBoxJsonObject.put(entry.getKey(), positions);
        }

        // 输出 JSON 数据
        logger.info("boxDataList JSON 数据：");
        logger.info(boxDataJsonArray.toString());

        logger.info("\nfullBoxMaterialBoxNumbers JSON 数据：");
        logger.info(fullBoxJsonObject.toString());

        logger.info("\nnonFullBoxMaterialPositions JSON 数据：");
        logger.info(nonFullBoxJsonObject.toString());

        // 解析 JSON 数据
        parseJsonData(boxDataJsonArray, fullBoxJsonObject, nonFullBoxJsonObject);

        Map boxData = new HashMap<>();
        boxData.put("boxDataList", boxDataList);
        boxData.put("fullBoxMaterialBoxNumbers", fullBoxMaterialBoxNumbers);
        boxData.put("nonFullBoxMaterialPositions", nonFullBoxMaterialPositions);

        boxData.put("boxDataJsonArray", boxDataJsonArray);
        boxData.put("fullBoxJsonObject", fullBoxJsonObject);
        boxData.put("nonFullBoxJsonObject", nonFullBoxJsonObject);
        return boxData;
    }

    public void parseJsonData(JSONArray boxDataJsonArray, JSONObject fullBoxJsonObject, JSONObject nonFullBoxJsonObject) {
        // 解析 boxDataJsonArray
        logger.info("\n解析 boxDataJsonArray：");
        for (int i = 0; i < boxDataJsonArray.size(); i++) {
            JSONObject boxData = boxDataJsonArray.getJSONObject(i);
            int boxId = boxData.getInteger("boxId");
            String boxType = boxData.getString("boxType");
            String drillInfos = boxData.getString("drillInfos");

            logger.info("盒子 " + boxId + " 类型: " + boxType + ", 信息: " + drillInfos);
        }

        // 解析 fullBoxJsonObject
        logger.info("\n解析 fullBoxJsonObject：");
        for (String material : fullBoxJsonObject.keySet()) {
            JSONArray boxNumbers = fullBoxJsonObject.getJSONArray(material);
            logger.info("料号 " + material + " 出现在盒子: " + boxNumbers.toString());
        }

        // 解析 nonFullBoxJsonObject
        logger.info("\n解析 nonFullBoxJsonObject：");
        for (String material : nonFullBoxJsonObject.keySet()) {
            JSONArray positions = nonFullBoxJsonObject.getJSONArray(material);
            logger.info("料号 " + material + " 出现在位置: " + positions.toString());
        }
    }

    /**
     * 从文件生成配针工单
     * @param wmsConfigInfo
     * @return
     */
    private List<String> getDrillinfoList(WmsConfigInfo wmsConfigInfo) {
        List<String> list = new ArrayList<>();
        try {
            String fileDir = wmsConfigInfo.getFilePath().replace("profile", "czapp/uploadPath");
            logger.info("edit fileDir is "+fileDir);
            List<ExcelDrillParser.Diameter> lsit = ExcelDrillParser.parseExcel(fileDir);
            for (int i = 0; i < lsit.size(); i++) {
                ExcelDrillParser.Diameter diameter = lsit.get(i);
                String drinninfo = diameter.getDrillDiameter().replace(".", "");

                logger.info(diameter.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.toString());
        }
        return list;
    }

    private WmsTxnInfo genWmsTxnInfo(String reqBody, String resBody, String drillInfo) {

//        String taskType, String drillCount, String m_Drill_ID, String boxCode,/
//        String drillSize = drillInfo.substring(0, 4);
//        String drillType = "" + drillInfo.charAt(4);
//        int drillCount = 50;
//        int drillGrindCount = new Integer(drillInfo.charAt(9)).intValue();

        WmsTxnInfo wmsTxnInfo = new WmsTxnInfo();
//        wmsTxnInfo.setTxnId(UUID.randomUUID().toString());
        wmsTxnInfo.setTxnType(BusinessConstants.TXN_TYPE_BIND_DRILLINFO);
        wmsTxnInfo.setReqBody(reqBody);
        wmsTxnInfo.setResBody(resBody);
        wmsTxnInfo.setMacCode(macCode);
        wmsTxnInfo.setTxnType(BusinessConstants.TXN_TYPE_REQUEST_MATERIAL);
        wmsTxnInfo.setCreateTime(DateUtils.getNowDate());
        wmsTxnInfo.setMacCode(macCode);
        wmsTxnInfo.setCreateBy(macCode);
        return wmsTxnInfo;
    }

    @GetMapping("/configMonitor")
    public AjaxResult configMonitor() {
        List<Map<String, Object>> needleBoxes = new ArrayList<>();

        // 模拟数据，实际应从数据库获取
        for (int boxId = 1; boxId <= 16; boxId++) {
            Map<String, Object> box = new HashMap<>();
            box.put("id", boxId);

            List<Map<String, Object>> positions = new ArrayList<>();
            for (int posId = 1; posId <= 50; posId++) {
                Map<String, Object> position = new HashMap<>();
                position.put("id", posId);
                position.put("status", (int)(Math.random() * 4)); // 随机状态
                positions.add(position);
            }

            box.put("positions", positions);
            needleBoxes.add(box);
        }

        return AjaxResult.success().put("needleBoxes", needleBoxes);
    }

    //只有配针盘的一种料
    private List<Map<String, String>> genConfigMap(String content) {
        logger.info("genConfigMap开始处理，content: {}", content);

        try {
            if(content == null || content.trim().isEmpty()) {
                logger.error("配针内容为空");
                return new ArrayList<>();
            }

            List<String> list = Arrays.asList(content.split(","));
            logger.info("分割后的列表大小: {}", list.size());

            List<Map<String, String>> configList = new ArrayList<>();
            Map<String, String> configMap = new HashMap<>();
            int j = 0;

            for (int i = 0; i < list.size(); i++) {
                String configKey = "Config" + ((i + 1) - (800*j));
                String configValue = list.get(i).toString().trim();
                configMap.put(configKey, configValue);
                logger.debug("{} = {}", configKey, configValue);

                if (i > 0 && ((i + 1) % 800 == 0 || (i + 1 == list.size()))) {
                    j++;
                    logger.info("添加配置组 {}, 包含 {} 个配置项", j, configMap.size());
                    configList.add(new HashMap<>(configMap)); // 创建副本避免引用问题
                    configMap.clear(); // 清空以备下次使用
                }
            }

            logger.info("genConfigMap完成，返回 {} 个配置组", configList.size());
            return configList;

        } catch (Exception e) {
            logger.error("genConfigMap处理异常", e);
            throw new RuntimeException("配针配方解析失败: " + e.getMessage(), e);
        }
    }

    private List<Map<String, String>> genConfigMapII(int axles, String content) {
        logger.info("genConfigMap开始处理，axles: {}, content: {}", axles, content);

        try {
            if (content == null || content.trim().isEmpty()) {
                logger.error("配针内容为空");
                return new ArrayList<>();
            }

            List<String> list = Arrays.asList(content.split(","));
            int configItemCount = list.size(); // 配置项数量
            logger.info("分割后的列表大小: {}", configItemCount);

            // 根据配置项数量确定每个托盘最多可以配置的份数
            int maxCopiesPerTray;
            if (configItemCount <= 200) {
                maxCopiesPerTray = 4;
            } else if (configItemCount <= 400) {
                maxCopiesPerTray = 2;
            } else {
                maxCopiesPerTray = 1;
            }

            logger.info("配置项数量: {}, 每个托盘最多可配置 {} 份", configItemCount, maxCopiesPerTray);

            List<Map<String, String>> configList = new ArrayList<>();
            int remainingAxles = axles;
            int trayIndex = 0;

            // 计算需要的托盘数量
            int trayCount = (int) Math.ceil((double) axles / maxCopiesPerTray);
            logger.info("总共需要 {} 个托盘", trayCount);

            while (remainingAxles > 0) {
                Map<String, String> trayConfigMap = new HashMap<>();
                int copiesInThisTray = Math.min(remainingAxles, maxCopiesPerTray);

                logger.info("开始处理托盘 {}，包含 {} 份配置", trayIndex + 1, copiesInThisTray);

                // 当前托盘的总配置项数量
                int totalItemsInTray = configItemCount * copiesInThisTray;

                // 为当前托盘生成配置
                int globalConfigIndex = 0;
                for (int copyIndex = 0; copyIndex < copiesInThisTray; copyIndex++) {
                    // 计算当前份的起始和结束编号
                    int startNumber, endNumber;
                    if (configItemCount <= 200) {
                        startNumber = copyIndex * 200 + 1;
                        endNumber = startNumber + configItemCount - 1;
                    } else if (configItemCount <= 400) {
                        startNumber = copyIndex * 400 + 1;
                        endNumber = startNumber + configItemCount - 1;
                    } else {
                        startNumber = 1;
                        endNumber = configItemCount;
                    }

                    logger.debug("第 {} 份配置，编号范围: {}-{}", copyIndex + 1, startNumber, endNumber);

                    // 添加当前份的配置项
                    for (int itemIndex = 0; itemIndex < configItemCount; itemIndex++) {
                        String configKey = "Config" + (startNumber + itemIndex);
                        String configValue = list.get(itemIndex).trim();
                        trayConfigMap.put(configKey, configValue);
                        globalConfigIndex++;

                        logger.trace("{} = {}", configKey, configValue);

                        // 安全检查：确保不超过800个配置项
                        if (globalConfigIndex >= 800) {
                            logger.warn("托盘 {} 已达到800个配置项上限", trayIndex + 1);
                            break;
                        }
                    }

                    // 如果当前托盘已满，跳出循环
                    if (globalConfigIndex >= 800) {
                        break;
                    }
                }

                logger.info("托盘 {} 配置完成，包含 {} 个配置项", trayIndex + 1, trayConfigMap.size());
                configList.add(trayConfigMap);

                remainingAxles -= copiesInThisTray;
                trayIndex++;
            }

            logger.info("genConfigMap完成，返回 {} 个托盘配置", configList.size());
            return configList;

        } catch (Exception e) {
            logger.error("genConfigMap处理异常", e);
            throw new RuntimeException("配针配方解析失败: " + e.getMessage(), e);
        }
    }

    private List<Map<String, String>> genConfigMap(int axles, String content) {
        logger.info("genConfigMap开始处理，axles: {}, content: {}", axles, content);

        try {
            if (content == null || content.trim().isEmpty()) {
                logger.error("配针内容为空");
                return new ArrayList<>();
            }

            List<String> list = Arrays.asList(content.split(","));
            int configItemCount = list.size();
            logger.info("分割后的列表大小: {}", configItemCount);

            // 确定每个托盘最多份数
            int maxCopiesPerTray;
            if (configItemCount <= 200) {
                maxCopiesPerTray = 4;
            } else if (configItemCount <= 400) {
                maxCopiesPerTray = 2;
            } else {
                maxCopiesPerTray = 1;
            }

            List<Map<String, String>> configList = new ArrayList<>();
            int remainingAxles = axles;
            int trayIndex = 0;

            while (remainingAxles > 0) {
                Map<String, String> configMap = new HashMap<>();
                int copiesInThisTray = Math.min(remainingAxles, maxCopiesPerTray);
                int configsAdded = 0;
                boolean trayFull = false;

                // 为当前托盘添加配置
                for (int copy = 0; copy < copiesInThisTray && !trayFull; copy++) {
                    int startNumber;
                    if (configItemCount <= 200) {
                        startNumber = copy * 200 + 1;
                    } else if (configItemCount <= 400) {
                        startNumber = copy * 400 + 1;
                    } else {
                        startNumber = 1;
                    }

                    for (int i = 0; i < configItemCount; i++) {
                        if (configsAdded >= 800) {
                            trayFull = true;
                            break;
                        }

                        String configKey = "Config" + (startNumber + i);
                        String configValue = list.get(i).trim();
                        configMap.put(configKey, configValue);
                        configsAdded++;
                    }
                }

                logger.info("托盘 {} 配置完成，包含 {} 份配置，{} 个配置项",
                        trayIndex + 1, Math.min(copiesInThisTray, configMap.size() / configItemCount), configMap.size());

                configList.add(configMap);
                remainingAxles -= copiesInThisTray;
                trayIndex++;
            }

            logger.info("genConfigMap完成，返回 {} 个托盘配置", configList.size());
            return configList;

        } catch (Exception e) {
            logger.error("genConfigMap处理异常", e);
            throw new RuntimeException("配针配方解析失败: " + e.getMessage(), e);
        }
    }

    /*
    private void notifyFrontend() {
        // 发送消息到前端，可以使用WebSocket或轮询等方式
        // 示例：使用WebSocket发送消息
        WebSocketServer.sendMessage("dataChanged");
    }
*/
    @PreAuthorize("@ss.hasPermi('business:configinfo:list')")
    @PostMapping("/rollbackdata")
    public TableDataInfo rollbackdata(WmsConfigInfo wmsConfigInfo)
    {

        wmsConfigInfoService.rollbackData();
        SysUser user = SecurityUtils.getLoginUser().getUser();

        Long userId = user.getUserId();

        // 构造推送消息（包含完整任务信息）
        Map<String, Object> payload = new HashMap<>();
        payload.put("taskId", UUID.randomUUID().toString());
        payload.put("businessData", "数据变更详情");
        payload.put("type", "CONFIRMATION_ALERT");

        List<WmsConfigInfo> list = wmsConfigInfoService.selectWmsConfigInfoList(wmsConfigInfo);
        return getDataTable(list);
    }

}
